package com.lis.scf.security;


import com.alibaba.fastjson.JSON;
//import com.example.rbac.common.dto.ResponseDTO;
//import com.example.rbac.entity.User;
//import com.example.rbac.repository.UserRepository;
import com.lis.scf.common.dto.ResponseDTO;
import com.lis.scf.entity.User;
import com.lis.scf.repository.UserRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 登录成功处理器
 */
@Component
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final UserRepository userRepository;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        // 更新最后登录时间
        User user = (User) authentication.getPrincipal();
        user.setLastLoginTime(LocalDateTime.now());
        userRepository.save(user);

        // 构建响应
        response.setContentType("application/json;charset=UTF-8");
        ResponseDTO<Object> success = ResponseDTO.success(authentication.getPrincipal());
        response.getWriter().write(JSON.toJSONString(success));
    }
}
